import { css } from './styles.js';
import '@shoelace-style/shoelace/dist/components/button/button.js';
import '@shoelace-style/shoelace/dist/components/input/input.js';
import '@shoelace-style/shoelace/dist/components/textarea/textarea.js';
import '@shoelace-style/shoelace/dist/components/radio-group/radio-group.js';
import '@shoelace-style/shoelace/dist/components/radio/radio.js';
import '@shoelace-style/shoelace/dist/components/checkbox/checkbox.js';
import '@shoelace-style/shoelace/dist/components/icon/icon.js';
import '@shoelace-style/shoelace/dist/components/icon-button/icon-button.js';
import '../../../utils/shoelace-config.js';
import { 
    render, 
    bindEvents, 
    openModal, 
    closeModal 
} from './scripts.js';
import {autoLogin} from "../../common/autoLogin";
import {localStore} from "../../../Store/localStore";
import {openLogin} from "../../common/openLogin";

class UserPublish extends HTMLElement {
    constructor() {
        super();
        this.attachShadow({ mode: 'open' });
        
        // 初始化状态
        this.isOpen = false;
        this.isLoading = false;

        (async ()=>{
             await autoLogin();
        })();

        if(localStore.get("token"))
            render(this.shadowRoot, css);
    }

    connectedCallback() {
        setTimeout(() => {
            if(localStore.get("token") && this.shadowRoot && this.shadowRoot.innerHTML.trim()) {
                bindEvents(this);
            }
        });
    }

    // 公共方法：程序化打开/关闭弹窗
    open() {
        if(localStore.get("token")) {
            // 确保组件已经渲染
            if (!this.shadowRoot.innerHTML.trim()) {
                render(this.shadowRoot, css);
                setTimeout(() => {
                    bindEvents(this);
                    openModal(this);
                }, 0);
            } else {
                openModal(this);
            }
        } else {
            // 如果用户没有登录，自动打开登录页面
            openLogin();
        }
    }

    close() {
        if(localStore.get("token"))
            closeModal(this);
    }
}

// 注册自定义元素
window.customElements.define('user-publish', UserPublish);